package com.lct.simpleforecast.mvp.presenter

import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.lct.simpleforecast.ActivityManager
import com.lct.simpleforecast.AppConstant
import com.lct.simpleforecast.R
import com.lct.simpleforecast.bean.ForecastBean
import com.lct.simpleforecast.delegates.DelegatesExt
import com.lct.simpleforecast.mvp.model.MainModel
import com.lct.simpleforecast.mvp.model.network.IRequest
import com.lct.simpleforecast.mvp.presenter.base.BasePresenter
import com.lct.simpleforecast.mvp.view.IMainView
import com.lct.simpleforecast.ui.activity.MainActivity
import okhttp3.Call

/**
 * Author：SkySmile
 * Date：2018/7/5
 * Description：MainActivity的presenter
 */
class MainPresenter : BasePresenter<IMainView>() {
    //当前的位置
    private var currentLocation: String by DelegatesExt.preference(AppConstant.SP_KEY_LOCATION,
            "")
    private val mainModel = MainModel()

    private var call: Call? = null

    //正在加载天气数据时，弹出了切换位置对话框，用户选择切换位置，原来的请求是否手动取消
    private var isCancel = false

    /**
     * 启动定位
     *
     * @param currentLocation 当前的位置
     */
    fun startLocation(currentLocation: String) {
        if (currentLocation == "") {
            //暂未设置位置
            view?.onLocationLoading("正在定位您的位置…")
        }
        mainModel.getLocationInfoByAMap(object : IRequest<String> {
            /**
             * 网络不可用
             */
            override fun onNetworkError() {
                if (currentLocation == "") {
                    view?.onNetWorkError(MainActivity.FIRST_LOCATION)
                }
            }

            /**
             * 请求成功
             */
            override fun onSuccess(t: String) {
                if (currentLocation == "") {
                    //暂未设置位置
                    view?.hideLoading()
                    view?.setTitle(t)
                    view?.onLocationSuccess(t)
                } else if (currentLocation != t) {
                    //位置发生改变，弹出对话框提示
                    showLocationChangeDialog(currentLocation, t)
                }
            }

            /**
             * 请求失败
             */
            override fun onFailure(errorMsg: String) {
                if (currentLocation == "") {
                    //暂未设置位置
                    view?.onLocationFail(errorMsg)
                }
            }
        })
    }

    /**
     * 获取天气数据
     *
     * @param location 城市名称 | 城区名称 （上海 | 浦东新区）
     * @param isRefresh 是否是刷新调用
     */
    fun getForecastData(location: String, isRefresh: Boolean = false): Call? {
        if (!isRefresh) {
            view?.showLoading()
        }
        call = mainModel.getForecastData(location, object : IRequest<ForecastBean> {
            /**
             * 网络不可用
             */
            override fun onNetworkError() {
                view?.onNetWorkError(MainActivity.GET_FORECAST_DATA, isRefresh)
            }

            /**
             * 请求成功
             */
            override fun onSuccess(t: ForecastBean) {
                if (t.status() == "ok") {
                    if (!isRefresh) {
                        view?.hideLoading()
                    }
                    view?.onLoadSuccess(t, isRefresh)
                } else {
                    view?.onLoadFailure(t.status(), isRefresh)
                }
            }

            /**
             * 请求失败
             */
            override fun onFailure(errorMsg: String) {
                if (isCancel) {
                    //正在加载数据时，弹出了切换位置的对话框，不对数据加载错误做处理
                    isCancel = false
                } else {
                    //其它情况，显示数据加载错误页面
                    view?.onLoadFailure(errorMsg, isRefresh)
                }
            }
        })
        return call
    }

    /**
     * 位置发生变化的提示
     *
     * @param oldLocation 原来的位置
     * @param newLocation 新的位置
     */
    private fun showLocationChangeDialog(oldLocation: String, newLocation: String) {
        MaterialDialog.Builder(ActivityManager.instance.currentActivity())
                .title(R.string.dialog_title)
                .content(R.string.change_location, oldLocation, newLocation)
                .negativeText(R.string.cancel)
                .positiveText(R.string.ok)
                .onAny { _, which ->
                    if (which == DialogAction.POSITIVE) {
                        //如果原来的请求正在执行，取消原来的请求
                        call?.let {
                            if (it.isExecuted) {
                                it.cancel()
                                isCancel = true
                            }
                        }
                        //切换位置
                        if (ActivityManager.instance.currentActivity() is MainActivity) {
                            //在MainActivity页面上弹出的对话框
                            view?.setTitle(newLocation)
                            view?.onLocationChange(newLocation)
                        } else {
                            //其它页面上弹出的对话框
                            currentLocation = newLocation
                            ActivityManager.instance.returnToActivity(MainActivity::class.java)
                        }
                    }
                }
                .build()
                .show()
    }

    override fun detachView() {
        super.detachView()
        call?.cancel()
    }
}